from flask import Blueprint, render_template, request
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.models.document import Document
from application import db
from flask import request, json
from qiniu import Auth
from qiniu import put_data
import time
from common.libs.DataHelper import getCurrentTime

document_page = Blueprint("document_page", __name__)


@document_page.route('/', methods=['GET', 'POST'])
def index():
    return ops_render("/common/document.html")


@document_page.route('/post', methods=['GET', 'POST'])
def document_post():
    content = request.form.get('content')
    title = request.form.get('title')
    type = request.form.get('type')
    weight = request.form.get('weight')

    if weight == "置顶" :
        a = Document.query.filter_by(weight="置顶").first()
        a.weight ="普通"
        db.session.commit()

        document = Document()
        document.content = content
        document.type = type
        document.weight = weight
        document.title = title
        document.created_time = document.updated_time = getCurrentTime()
        db.session.add(document)
        db.session.commit()
        return ops_render("/common/document.html")

    else:
        document = Document()
        document.content = content
        document.type = type
        document.weight = weight
        document.title = title
        document.created_time = document.updated_time = getCurrentTime()
        db.session.add(document)
        db.session.commit()
        return ops_render("/common/document.html")




@document_page.route('/submitimage', methods=['GET', 'POST'])
def submitImage():
    file = request.files['file']
    # 上传到七牛后保存的文件名
    key = str(int(time.time())) + file.filename
    # print file.filename
    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'guanzhuoran'
    # http://+外链域名
    domian_name = 'http://upload.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # ret, info = _form_put(token, key, file.read(),params=None,
    #          mime_type='application/octet-stream', crc=None)

    ret, info = put_data(token, key, file.read(), params=None,
                         mime_type='application/octet-stream')
    print(info)
    print(ret['key'])
    return '{"location":"' + domian_name + "/" + key + '"}'


@document_page.route('/getimg', methods=['GET', 'POST'])
def getImg():
    a = Document.query.filter_by(type="首页新闻").all()
    rts = []
    for item in a:
        temp = dict(image=item.image)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts
